package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dao.OrdersDao;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.service.*;
import com.itheima.reggie.service.exception.CustomException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {


    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrdersDao ordersDao;


    @Override
    public void submit(Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getThreadLocal();
        //查询用户信息
        User user = userService.getById(userId);

        //查询当前用户的购物车信息
        List<ShoppingCart> shopping = shoppingCartService.findShopping();
        if (shopping==null){
            throw new CustomException("购物车为空,不能下单");
        }


        //获取地址id
        Long addressBookId = orders.getAddressBookId();
        //获取地址id对应的地址信息
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null){
            throw new CustomException("地址信息有误,不能下单");
        }
        //生成订单号
        long orderId = IdWorker.getId();

        //组装订单总金额
        AtomicInteger amount = new AtomicInteger(0);//乐观锁,保证线程安全

        //添加订单明细表
        List<OrderDetail> listOrderDetail = shopping.stream().map(item ->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            //getAmount() = 菜品单价,.getNumber()菜品数量,intValue()转成int
            //这段代码的含义就是等于菜品单价乘以菜品数量
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());



        //添加订单表
        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表添加多条数据
        orderDetailService.saveBatch(listOrderDetail);


        //清空购物车
        shoppingCartService.deleteByUserId();
    }

    //查询订单
    @Override
    public Page<OrderDto> findPage(int page, int pageSize) {
        Page<Orders> pages = new Page<>(page,pageSize);

        Long userId = BaseContext.getThreadLocal();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Orders::getUserId,userId);

        lqw.orderByDesc(Orders::getOrderTime);

        Page<Orders> ordersPage = ordersDao.selectPage(pages, lqw);

        Page<OrderDto> dtoPage = new Page<>();

        List<OrderDto> records = ordersPage.getRecords().stream().map(order -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order,orderDto);

            //根据订单表的id对应订单明细表的dish_id查询订单明细表数据
            LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
            //select * from order_detail where
            lqw1.eq(OrderDetail::getOrderId,order.getId());

            List<OrderDetail> list = orderDetailService.list(lqw1);

            orderDto.setOrderDetails(list);

            return orderDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(records);


        return dtoPage;
    }

    @Override
    public Page<Orders> findPageOrders(int page, int pageSize, String number, LocalDateTime beginTime, LocalDateTime endTime) {

        Page<Orders> p = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.eq(StringUtils.isNotBlank(number),Orders::getNumber,number);

        lqw.ge(beginTime !=null,Orders::getOrderTime,beginTime);
        lqw.le(endTime != null,Orders::getOrderTime,endTime);

        Page<Orders> ordersPage = ordersDao.selectPage(p, lqw);


        return ordersPage;
    }

    @Override
    public void updateStatus(Orders orders) {

        //获取当前订单id
        Long id = orders.getId();
        //获取当前状态
        Integer status = orders.getStatus();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Orders::getId,id);

        Orders orders1 = ordersDao.selectOne(lqw);

        orders1.setStatus(status);

        ordersDao.updateById(orders1);

    }


}
